import { Modal } from 'antd';
import * as React from 'react';
import _ from 'lodash';

// usage: <FormModal form={FormComponent} formProps={{ someProps }}/>
// 会在 fromProps 中放一个 afterSubmit 回调，用于关闭当前 Modal
// 当 formProps 中有 afterSubmit 时，会进行包装
// 推荐使用 SmartForm 来包装内部的 Form
class FormModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      visible: false
    };
  }

  show() {
    this.setState({ visible: true });
  }
  handleCancel() {
    this.setState({ visible: false });
  }
  afterSubmit(value) {
    const formProps = this.props.formProps || {};
    if (_.isFunction(formProps.afterSubmit)) {
      formProps.afterSubmit(value);
    }
    if (_.isFunction(this.props.afterSubmit)) {
      this.props.afterSubmit(value);
    }
    this.handleCancel();
  }

  render() {
    const FormClass = this.props.form;
    const formProps = this.props.formProps || {};

    return (
      <Modal
        {...this.props}
        visible={this.state.visible}
        footer={undefined}
        onCancel={::this.handleCancel}
      >
        <FormClass {...formProps} afterSubmit={::this.afterSubmit}/>
      </Modal>
    );
  }
}

export { FormModal };
